import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StudentTool {
    //学生工具类

    //文件名
    public static String FILE_NAME_STUDENT = "学生表.txt";
    public static final String FILE_NAME = "未提交名单.txt";
    //文件路径
    public static  String FILE_PATH = "F:\\homework\\"+FILE_NAME_STUDENT;


    //学生集合
    public static List<Student> studentList = new ArrayList<>();

    //当类加载时
    static {
        //从指定路径文件中读取学生并加入集合
        readStudentFromFile(FILE_PATH);
    }


    //方法,从指定路径文件中读取学生并加入集合
    // 方法,从指定路径文件中读取学生并加入集合，如果文件不存在或格式不对返回false
    public static boolean readStudentFromFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("File does not exist.");
            return false;
        }

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line;
            boolean validFormat = true;
            while ((line = reader.readLine()) != null) {
                // 按tab分割字符串
                String[] parts = line.split("\t");
                if (parts.length != 2) {
                    validFormat = false;
                    break;
                }

                try {
                    long id = Long.parseLong(parts[0]);
                    String name = parts[1];
                    Student student = new Student(id, name);
                    studentList.add(student);
                } catch (NumberFormatException e) {
                    validFormat = false;
                    break;
                }
            }

            if (!validFormat) {
                System.out.println("File format is incorrect.");
                studentList.clear(); // 可选：清除已添加的不完整或错误数据
                return false;
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    // 测试方法
    public static void main(String[] args) {
        boolean success = readStudentFromFile(FILE_PATH);
        if (success) {
            for (Student student : studentList) {
                System.out.println(student);
            }
        } else {
            System.out.println("文件不存在");
        }
    }
}
